/**
 * @api post controller.
 *
 * User: yunshengzhu
 * Date: 2020-02-12
 * Time: 18:43
 */
package control

import (
	"card-platform/config"
	"card-platform/model"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/usthooz/wxsign"
	redis "gopkg.in/redis.v3"
	"pkg/cfg"
	"pkg/utils"
	"time"
)

var sessionKeyMap = make(map[string]string)

var redisClient *redis.Client

const (
	UserTypConsumer = 1
	UserTypMerchant = 2
	UserTypAdmin    = 3
)

func init() {
	// 初始化缓存access_token及ticket的redis
	redisClient = redis.NewClient(&redis.Options{
		Addr: "172.20.177.71:16379",
	})

	wxsign.WxSignRdsInit(redisClient)
}

type User struct {
}

// swagger:operation POST /wxSign 用户类 wxSignReq
// ---
// summary: 授权登录 /wxSign.
// description: .
//// responses:
////   "200":
////     "$ref": "#/responses/userResp"
func (a *User) WxSign(userId int64, data []byte, param Param) (out interface{}, code int, err error) {
	req := WxSignReq{}
	err = json.Unmarshal(data, &req)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR_JSON, err
	}
	/*wxConfig := New(config.APPID, config.APPSECRET, req.Url)
	sign := wxConfig.GetWechatConfig()*/
	ws := wxsign.New(
		config.APPID,
		config.APPSECRET,
		// 缓存access_token使用的redis key
		"wxsign:token",
		// 缓存ticket使用的redis key
		"wxsign:ticket",
	)

	if len(req.Url) <= 0 {
		return nil, config.ERR, errors.New("url不能为空")
	}

	var sign *wxsign.WxJsSign

	sign, err = ws.GetJsSign(req.Url)
	if err != nil {
		//fmt.Print("Get js sign err-> %#v", err)
		sign, err = ws.GetJsSign(req.Url)
		if err != nil {
			//fmt.Print("Get js sign err-> %#v", err)
			return sign, config.ERR, err
		}
	}

	jsTicket, _ := ws.GetTicket()
	cfg.LogInfo("jsTicket:", jsTicket)
	return sign, config.OK, nil
}

// swagger:operation POST /authorizationCode 用户类 authorizationCodeReq
// ---
// summary: 授权登录 /authorizationCode.
// description: .
//// responses:
////   "200":
////     "$ref": "#/responses/userResp"
func (a *User) AuthorizationCode(userId int64, data []byte, param Param) (out interface{}, code int, err error) {
	req := AuthorizationCodeReq{}
	err = json.Unmarshal(data, &req)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR_JSON, err
	}
	res, err := WechatLogin(req.JsCode, config.APPID, config.APPSECRET)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, -1, err
	}

	cfg.LogInfo("res:", res)
	openId := res["openid"].(string)
	accessToken := res["access_token"].(string)
	user, err := model.GetUserOpenId(openId)
	if err != nil && err != model.ErrRecordNotFound {
		return nil, -1, err
	}

	if user.UserId <= 0 {
		var card model.CardDb
		if len(req.CardNumber) > 0 {
			card, err = model.GetCardNumber(req.CardNumber)
			if err != nil && err != model.ErrRecordNotFound {
				cfg.LogErr("err:", err)
				return
			}

			if card.Status != 1 {
				if card.CardPwd == req.CardPwd {
					user.PUserId = card.UserId
					user.Grade = 1
					user.ExpTime=time.Now().AddDate(2,0,0).Unix()
				}
			}
		}
		user.OpenId = openId
		user.CreateTime = time.Now().Unix()
		userInfo, err := GetWeixinInfo(accessToken, openId)
		if err != nil {
			cfg.LogErr("err:", err)
		}
		user.Typ = 1
		user.Nickname = userInfo.Name
		user.HeadImg = userInfo.HeadImgUrl
		user.Sex = userInfo.Sex
		err = model.CreateUser(user)
		if err != nil {
			cfg.LogErr("err:", err)
			return nil, config.ERR, err
		}

		if card.Status != 1 {
			//更新卡密和卡的归属用户
			if user.PUserId > 0 {
				card.Status = 1
				card.ToUserId = user.UserId
				card.UseTime = time.Now().Unix()

				err = model.UpdateCard(card)
				if err != nil {
					cfg.LogErr("err:", err)
				}

				//查询推荐用户数
				num, err := model.GetUserPUserIdCount(card.UserId)
				if err != nil {
					cfg.LogErr("err:", err)
				}

				if num >= 60 {
					//修改用户等级为砖石会员
					err = model.UpdateUserGrade(card.UserId, 3)
					if err != nil {
						cfg.LogErr("err:", err)
					}
				}

			}
		}

	} else if user.Grade == 0 && user.PUserId == 0 {
		if len(req.CardNumber) > 0 {
			card, err := model.GetCardNumber(req.CardNumber)
			if err != nil && err != model.ErrRecordNotFound {
				cfg.LogErr("err:", err)
			}

			if card.CardPwd == req.CardPwd && card.Status != 1 {
				card.Status = 1
				card.ToUserId = user.UserId
				card.UseTime = time.Now().Unix()
				err = model.UpdateCard(card)
				if err != nil {
					cfg.LogErr("err:", err)
				}
				user.PUserId = card.UserId
				//更新用户会员等级
				user.ExpTime=time.Now().AddDate(2,0,0).Unix()
				err = model.UpdateUserGradePUserId(user.UserId, 1, card.UserId,user.ExpTime)
				if err != nil {
					cfg.LogErr("err:", err)
				}

			}
		}
	}

	// 更新token
	user.Token = utils.MyMd5(fmt.Sprintf("%d%s%s", time.Now().UnixNano(), user.OpenId, utils.GetRandomStrToken(20)))
	err = model.UpdateUserToken(user.UserId, user.Token)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR, err
	}

	ws := wxsign.New(
		config.APPID,
		config.APPSECRET,
		// 缓存access_token使用的redis key
		"wxsign:token",
		// 缓存ticket使用的redis key
		"wxsign:ticket",
	)

	t, _ := ws.GetAccessToken()
	ress, _ := UserInfo(t, user.OpenId)
	user.Subscribe = ress.Subscribe
	user.Wx = res
	return user, config.OK, nil
}

func CheckUserAuth(token string, userId int64) (int64, error) {
	user, err := model.GetUserToken(token)
	if err != nil && err != model.ErrRecordNotFound {
		cfg.LogErr("err:", err)
		return 0, err
	}
	if user.UserId <= 0 {
		return 0, errors.New("用户未登录")
	}

	if user.UserId != userId {
		return 0, errors.New("用户权限验证失败")
	}

	return user.UserId, nil
}

type wxUserInfo struct {
	PhoneNumber     string `json:"phoneNumber"`
	PurePhoneNumber string `json:"purePhoneNumber"`
	CountryCode     string `json:"countryCode"`
	Watermark       struct {
		Timestamp int64  `json:"timestamp"`
		Appid     string `json:"appid"`
	} `json:"watermark"`
}

type userInfo struct {
	OpenId    string `json:"openId"`
	NickName  string `json:"nickName"`
	Gender    int    `json:"gender"`
	AvatarUrl string `json:"avatarUrl"`
	watermark struct {
		Timestamp int64  `json:"timestamp"`
		Appid     string `json:"appid"`
	}
}
